import React, { useEffect, useState } from 'react';
import { Button, Card } from 'antd';
import styles from './index.less';
import SoundOutlined from '@ant-design/icons/lib/icons/SoundOutlined';
import { CheckCircleOutlined, CheckOutlined, Popup, udp } from '@cscec/udp-mobile-ui';
import { Image, Modal } from 'antd-mobile';
import ExclamationCircleOutlined from '@ant-design/icons/lib/icons/ExclamationCircleOutlined';
import { Uphistory } from '@/pages/Schme/service';
import { UnorderedListOutlined } from '@ant-design/icons';
import { StarFill, StarOutline } from 'antd-mobile-icons';
import { updateScore } from '@/pages/Textbook/service';
import { useAudioPlay } from "@/hooks/useAudioPlay";
import audioPlayer from '../../utils/audioPlayer';
const WordImagePairing = ({ values, num, length, setNum, wordList }: any) => {
  const [selectedImage, setSelectedImage] = useState<string | null>(null);
  const [isError, setIsError] = useState<boolean>(false);
  const { isPlaying, isLoading, playAudio, stopAudio } = useAudioPlay({});
  const word = values?.name

  const unitNum = wordList[0]?.unitIdEXName.substring(0, 1)
  useEffect(() => {//只在第一次播放
    if (word) {
      //这里会播放单词的音频
     playAudio(word)
    }
  }, [word])
  // 图片选项数据
  const imageOptions = values.tbExerciseOptionVos.map((element) => {
    return {
      imageUrl: element.imgUrl,
      id: element.answer == 1 ? word : element.id
    }
  });
  // 播放单词发音
  const playWordSound = () => {
    //这里会播放单词的音频
      playAudio(word)
  };
  //控制弹窗
  const [visible, setVisible] = useState(false)
  const [visible1, setVisible1] = useState(false)
  // 所有单词弹窗
  const [modalvisible, setModalvisible] = useState(false)
  const [current, setCurrent] = useState(1)
  //是否第一次选对
  const [isFirstTrue, setIsFirstTrue] = useState(true)

  //翻页功能
  const next = async () => {
    const result =  updateScore({//异步一下，不等接口回来
      unitId: values.unitId,
      type: 0,
      flag: isFirstTrue ? 0 : 1
    })
    if (num + 1 > length) {
      Uphistory({
        textbookId: values.textbookId,
        unitId: values.unitId,
        topicId: values.topicId,
        exerciseId: values.id,
        completionStatus: 2, studyFlag: 1, historyType: 1
      }).then((rt) => {
        udp.message('当前主题已经学习完毕!')
        udp.close()
      })
    } else {
      //翻页时，设置回true
      setIsFirstTrue(true)
      Uphistory({
        textbookId: values.textbookId,
        unitId: values.unitId,
        topicId: values.topicId,
        exerciseId: values.id,
        completionStatus: 2,
        studyFlag: 1, historyType: 1
      })
      setNum(num + 1)
    }
  }
  const mesArr = ['Great job!', 'Awesome!！', 'Wow, so clever!', 'Perfect!', 'High five!', 'Brilliant!', 'Way to go!', 'You’re amazing!', 'Keep up the good work!']
  const index = Math.floor(Math.random() * (8))
  const errorArr = ['Oops! Try again', 'Not yet.Try again!', 'Almost! Try once more', 'Another try!', 'Not right.Try again!', 'Keep going!']
  const errIndex = Math.floor(Math.random() * (6))

  // 继续按钮处理
  const handleContinue = () => {
    if (selectedImage) {
      if (selectedImage == word) {
        audioPlayer.playSuccess();//播放音效
        setVisible(true)
        setIsError(false)
      } else {
        audioPlayer.playFailure();//播放音效
        setIsFirstTrue(false)//这里设置不是第一次选对了
        setIsError(true)
        setVisible1(true)
      }
    } else {
      udp.alert('请选择对应图片')
    }
  };

  const handleAllWord = () => {
    setModalvisible(true)
  }
  return (
    <>
      <div className={styles["word-header"]}>
        <div className={styles["word"]}>单词{num}/{length}</div>
        <div className={styles["word"]} onClick={handleAllWord}>
          <UnorderedListOutlined />
          所有单词
        </div>

      </div>
      <div className={styles["word-section"]}>
        <div className={styles["word-display"]}>
          {word}
        </div>
        <div className={styles["icon-div"]} onClick={playWordSound}>
          <SoundOutlined className={styles["sound-icon"]} />
        </div>
      </div>

      <div className={styles["images-grid"]}>
        {imageOptions.map((option) => (
          <div
            key={option.id}
            className={selectedImage === option.id ? styles["image-option-selected"] : styles["image-option"]}
            onClick={() => {
              setSelectedImage(option.id)
              //playWordSound()
            }}
            style={{
               backgroundColor:'#ffffff'
            }}
          >
            <div className={styles["image-container"]} style={{borderColor: (isError && selectedImage == option.id) ? 'red' : '' }}>
              <Image
                src={option.imageUrl}
                //alt={option.label}
                fit='contain'
                lazy
                className={styles["option-image"]}
              />
              {/* {selectedImage === option.id && (
                  <div className={styles["selection-indicator"]}>
                    <CheckOutlined />
                  </div>
                )} */}
            </div>
          </div>
        ))}
      </div>

      <div className={styles["actions"]}>
        <Button
          size="large"
          onClick={handleContinue}
          className={styles["continue-button"]}
          disabled={!selectedImage}
          block
        >
          Check
        </Button>
      </div>
      <Popup
        visible={visible}
        bodyStyle={{
          height: '35vh',
          backgroundColor: '#ffffff',
          borderRadius: '25px 25px 0 0',
          textAlign: 'center',
        }}
      >
        <div
          style={{
            height: '180px',
            color: '#4caf50',
            fontSize: '30px',
            fontWeight: 'bold',
            padding: '50px'
          }}>
          <CheckCircleOutlined
            style={{
              color: '#4caf50',
              fontSize: 'xxx-large',
              display: 'block'
            }} />
          {mesArr[index]}</div>

        <Button
          size="large"
          onClick={() => {
            setIsError(false)
            setVisible(false)
            next()
          }}
          className={styles["continue-button"]}
          style={{
            width: '90%',
            backgroundColor: '#4caf50',
            color: '#ffffff'
          }}
          disabled={!selectedImage}
          block
        >
          Next
        </Button>
      </Popup>
      <Popup
        visible={visible1}
        bodyStyle={{
          height: '35vh',
          background: '#ffffff',
          textAlign: 'center',
          borderRadius: '25px 25px 0 0'
        }}
      >
        <div
          style={{
            height: '180px',
            color: 'red',
            fontSize: '30px',
            fontWeight: 'bold',
            padding: '50px'
          }}>
          <ExclamationCircleOutlined style={{
            color: 'red',
            fontSize: 'xxx-large',
            display: 'block'
          }} />
          {errorArr[errIndex]}</div>
        <Button
          size="large"
          onClick={() => {
            setVisible1(false)
            setSelectedImage(null)
            setIsError(false)
            //next()
          }}
          className={styles["continue-button"]}
          style={{
            width: '90%',
            color: '#ffffff',
            backgroundColor: '#f44336'
          }}
          disabled={!selectedImage}
          block
        >
          Try Again
        </Button>
      </Popup>
      <Modal visible={modalvisible}
        bodyClassName={styles["list-modal"]}
        content={
          <div className={styles["list-content"]}>
            <h3 className={styles['list-title']}>{`Unit ${unitNum}：所有单词`}</h3>
            <p className={styles['header-title']}>点击单词直接跳转学习</p>
            <div className={styles["word-list"]}>
              {wordList.map((item, index) => {
                return <div className={current === index + 1 ? styles["word-item-current"] : styles["word-item"]}
                  onClick={() => {
                    setCurrent(index + 1)
                    setNum(index + 1)
                    setModalvisible(false)
                  }}>
                  {item.type == 2 ? <span>{item.name}</span> : <Image
                    src={item.imgUrl}
                    height='21px'
                    fit='contain'
                  />}
                  <StarFill className={current === index + 1 ? styles["word-inco-current"] : styles["word-inco"]} />
                </div>
              })}
            </div>
            <Button className={styles["close-button"]}
              onClick={() => {
                setModalvisible(false)
              }}>关闭</Button>
          </div >
        }

        closeOnAction
        closeOnMaskClick={true}
        onClose={() => {
          setModalvisible(false)
        }}
      >

      </Modal >
    </>
  );
};

export default WordImagePairing;